using System;

namespace Sunny.UI;

public static class EnumEx
{
	public static string DisplayText(this Enum value)
	{
		DisplayTextAttribute customAttribute = value.GetType().GetField(value.ToString()).GetCustomAttribute<DisplayTextAttribute>();
		if (customAttribute == null)
		{
			return value.ToString();
		}
		return customAttribute.DisplayText;
	}

	public static TEnum ToEnum<TEnum>(this string dataToMatch, bool ignoreCase = true) where TEnum : struct
	{
		if (!dataToMatch.InEnum<TEnum>()())
		{
			return (TEnum)Enum.Parse(typeof(TEnum), dataToMatch, ignoreCase);
		}
		return default(TEnum);
	}

	public static Func<bool> InEnum<TEnum>(this string dataToCheck) where TEnum : struct
	{
		return () => string.IsNullOrEmpty(dataToCheck) || !Enum.IsDefined(typeof(TEnum), dataToCheck);
	}
}
